import time
import threading
from concurrent.futures import ThreadPoolExecutor
from ..apps.master_window import GcanViewTemplate


class WorkFlow:

    def __init__(self, mainView:GcanViewTemplate,parentView=None, stepCounts=5):
        # 主界面，自带CAN通信实例
        self.mainView = mainView
        # 启动工作流的界面，用于相互通讯
        self.parentView = parentView
        self._step = 0
        self._stepCounts = stepCounts
        self.handle_dict = {}
        self.pool = ThreadPoolExecutor(max_workers=3)

        # 自动创建每个step的OverFlag信号
        for i in range(stepCounts):
            setattr(self, f"step{i}OverFlag", False)
        # 创建循环步数的每个工作函数
        self.setHandleDict()

    def setStepOverFlag(self, step):
        setattr(self, f"step{step}OverFlag", True)
    def resetStepOverFlag(self, step):
        setattr(self, f"step{step}OverFlag", False)

    def setHandleDict(self):
        for i in range(self.stepCounts):
            self.handle_dict[i] = getattr(self, "handleStep" + str(i), self.defaultHandle)

    def defaultHandle(self):
        time.sleep(1)
        print("defaultHandle")
        self.nextStep()
        pass
    
    @property
    def stepCounts(self):
        return self._stepCounts

    def nextStep(self):
        if self._step < self.stepCounts - 1:
            self._step += 1
        else:
            self.resetStep()
    
    def prevStep(self):
        if self._step > 0:
            self._step -= 1
    
    def resetStep(self):
        self._step = 0
    
    def getStep(self):
        return self._step
    
    def setStep(self, step):
        self._step = step


    def handleStep0(self):
        time.sleep(1)
        print("step0")
        self.nextStep()

    
    def handleStep1(self):
        time.sleep(1)
        print("step1")
        self.nextStep()

    def handleStep2(self):
        time.sleep(1)
        print("step2")
        self.nextStep()

    def handleStep3(self):
        time.sleep(1)
        print("step3")
        self.nextStep()
    


    def set_handle_steps(self, step, handle):
        self.handle_dict[step] = handle

    def refreshMainViewStep():
        NotImplementedError("refreshMainViewStep is not implemented")
        pass
    
    def _run(self):
        while True:
            time.sleep(0.5)
            self.refreshMainViewStep()
            self.handle_dict[self._step]()
            # FIXME: 考虑到可能需要自定义步数跳转，所以把nextStep放到handle函数中
            # self.nextStep()
    
    def run(self):
        # print('workflow run....')
        # 用一个单独线程来执行工作流
        self.pool.submit(self._run)
        # self._run()
        pass

def main():
    wf = WorkFlow(None)
    wf.run()
    pass
    
if __name__ == '__main__':
    main()